package com.seeyon.apps.lzmzj.kit;

import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.ctpenum.dao.cache.CtpEnumItemCache;
import com.seeyon.ctp.common.exceptions.BusinessException;
import com.seeyon.ctp.common.log.CtpLogFactory;
import com.seeyon.ctp.common.po.ctpenumnew.CtpEnumItem;
import com.seeyon.ctp.organization.bo.V3xOrgAccount;
import com.seeyon.ctp.organization.bo.V3xOrgDepartment;
import com.seeyon.ctp.organization.bo.V3xOrgEntity;
import com.seeyon.ctp.organization.bo.V3xOrgMember;
import com.seeyon.ctp.organization.manager.OrgManager;
import com.seeyon.ctp.util.Strings;
import org.apache.commons.logging.Log;

import java.text.SimpleDateFormat;
import java.util.Iterator;
import java.util.List;

public class DataConversionKit {

    private static final Log log = CtpLogFactory.getLog(DataConversionKit.class);

    private static OrgManager orgManager = (OrgManager) AppContext.getBean("orgManager");
    private static CtpEnumItemCache ctpEnumItemCache = (CtpEnumItemCache) AppContext.getBean("ctpEnumItemCache");

    /**
     * 对数据类型进行转换
     *
     * @param fieldType  字段类型
     * @param fieldValue 字段值
     * @return 转换后的值
     */
    public static Object bpmDataConversion(String fieldType, Object fieldValue, String fieldDesc) throws Exception {
        Object value = "";
        String fieldValue_new = StrKit.str(fieldValue);
        if ("".equals(fieldValue_new)) {
            return "";
        }
        if ("imageselect".equals(fieldType) || "radio".equals(fieldType) || "select".equals(fieldType)) {
            if ("".equals(fieldValue_new)) {
                throw new BusinessException(fieldDesc + " 枚举编码[" + fieldValue_new + "]在OA系统中未匹配到对应枚举");
            }
            String fieldValueNew = "";
            if (fieldDesc.contains("_")) {
                fieldValueNew = fieldDesc.split("_")[0] + "_" + fieldValue_new;
            } else {
                fieldValueNew = fieldValue_new;
            }
            // 获取枚举项id
            CtpEnumItem ctpEnumItem = getEnumByCode(fieldValueNew);
            if (ctpEnumItem != null) {
                value = ctpEnumItem.getId();
            } else {
                throw new BusinessException(fieldDesc + " 枚举编码[" + fieldValue_new + "]在OA系统中未匹配到对应枚举");
            }
        } else if ("date".equals(fieldType)) {
            // 保留年月日时分秒
            if (!"".equals(fieldValue_new)) {
                if ("00000000".equals(fieldValue_new)) {
                    value = "";
                } else {
                    if (fieldValue_new.length() == 8) {
                        value = DateKit.getSimpleDate(fieldValue_new);
                    } else if (fieldValue_new.length() == 6) {
                        value = new SimpleDateFormat("MM").format(new SimpleDateFormat("yyyyMM").parse(fieldValue_new));
                    } else {
                        value = fieldValue_new;
                    }
                }
            } else {
                value = fieldValue_new;
            }

        } else if ("checkbox".equals(fieldType)) {
            if ("1".equals(fieldValue_new)) {
                value = "勾选";
            } else {
                value = "未勾选";
            }
        } else if ("textarea".equals(fieldType) || "text".equals(fieldType) || "linenumber".equals(fieldType)) {
            value = fieldValue_new;
        } else if ("department".equals(fieldType)) {
            if (!"".equals(fieldValue_new)) {
                // 根据部门编码获取部门id
                List<V3xOrgEntity> orgDeptList = orgManager.getEntityList(V3xOrgDepartment.class.getSimpleName(), "code", fieldValue_new, null, false, true);
                if (!orgDeptList.isEmpty()) {
                    value = orgDeptList.get(0).getId();
                } else {
                    if ("".equals(value)) {
                        log.info("部门编码[" + fieldValue_new + "]在OA系统中未匹配到对应部门");
                        throw new BusinessException(fieldDesc + " 部门编码[" + fieldValue_new + "]在OA系统中未匹配到对应部门");
                    }
                }
            }
        } else if ("account".equals(fieldType)) {
            if (!"".equals(fieldValue_new)) {
                // 根据单位编码获取单位id
                List<V3xOrgEntity> orgAccountList = orgManager.getEntityList(V3xOrgAccount.class.getSimpleName(), "code", fieldValue_new, null, false, true);
                if (!orgAccountList.isEmpty()) {
                    value = orgAccountList.get(0).getId();
                } else {
                    if ("".equals(value)) {
                        log.info("单位编码[" + fieldValue_new + "]在OA系统中未招到对应单位");
                        throw new BusinessException(fieldDesc + " 单位编码[" + fieldValue_new + "]在OA系统中未匹配到对应单位");
                    }
                }
            }
        } else if ("multimember".equals(fieldType)) {
            String dataValue = fieldValue_new;
            if (!"".equals(dataValue)) {
                String[] dataArray = dataValue.split(",");
                StringBuilder stb = new StringBuilder();
                for (String id : dataArray) {
                    // 根据成员id获取成员名称
                    String name = orgManager.getMemberById(Long.parseLong(id)).getName();
                    stb.append(name).append(",");
                }
                value = stb.toString().substring(0, stb.toString().length() - 1);
            }
        } else if ("member".equals(fieldType)) {
            if (!"".equals(fieldValue_new)) {
                // 根据成员编码获取成员id
                List<V3xOrgEntity> orgMemberList = orgManager.getEntityList(V3xOrgMember.class.getSimpleName(), "code", fieldValue_new, null, false, true);
                if (!orgMemberList.isEmpty()) {
                    value = orgMemberList.get(0).getId();
                } else {
                    if ("".equals(value)) {
                        log.info("人员编码[" + fieldValue_new + "]在OA系统中未招到对应账号");
                        throw new BusinessException(fieldDesc + " 人员编码[" + fieldValue_new + "]在OA系统中未匹配到对应账号");
                    }
                }
            }
        } else if ("datetime".equals(fieldType)) {
            // 将时间戳转换为yyyy-MM-dd HH:mm:ss格式
            if (!"".equals(fieldValue_new)) {
                if (fieldValue_new.length() < 11) {
                    value = fieldValue_new + " 00:00";
                } else {
                    value = fieldValue_new;
                }
            } else {
                value = fieldValue_new;
            }
        } else if ("attachment".equals(fieldType)) {
            value = "file_attachment_" + fieldValue_new;
        } else if ("image".equals(fieldType)) {
            value = "image_attachment_" + fieldValue_new;
        } else {
            value = fieldValue_new;
        }
        return value;
    }


    public static CtpEnumItem getEnumByCode(String itmeCode) {
        // 检查输入的枚举项代码是否为空或空白字符串
        if (Strings.isBlank(itmeCode)) {
            return null;
        } else {
            // 初始化一个账户ID变量，用于后续比较
            Long accountId = null;
            // 遍历枚举项缓存中的所有条目
            Iterator var4 = ctpEnumItemCache.findAll().iterator();

            while (var4.hasNext()) {
                CtpEnumItem entry = (CtpEnumItem) var4.next();
                // 如果accountId为null，且当前枚举项的代码与输入代码匹配，则返回该枚举项
                if (accountId == null) {
                    if (itmeCode.equals(entry.getEnumItemCode())) {
                        return entry;
                    }
                } else if (itmeCode.equals(entry.getEnumItemCode())) {
                    // 如果accountId不为null，且当前枚举项的代码与输入代码匹配，则返回该枚举项
                    return entry;
                }
            }
            // 如果遍历完成后仍未找到匹配的枚举项，则返回null
            return null;
        }
    }
}